﻿using System.IO;

using System.Security.Cryptography;
using System.Text;

namespace ciji.Core
{
    public class EncryptLibrary
    {
        private static byte[] cryptKey = new byte[] { 89, 92, 226, 162, 53, 81, 170, 154 };
        private static byte[] cryptIV = new byte[] { 92, 141, 249, 29, 6, 36, 70, 85, 2, 249, 132, 157, 157, 164, 24, 61, 147, 127, 106, 26, 52, 106, 205, 204, 225, 111, 226, 37, 212, 220, 70, 210 };
        public static string getkey()
        {
            return "56qqt@#@";
        }
        /// <summary>
        /// 固定密钥加密
        /// </summary>
        /// <param name="encryptText"></param>
        /// <returns></returns>
        public static string Encrypt(int encryptText)
        {
            return EncryptString(encryptText.ToString());
        }
        /// <summary>
        /// 固定密钥加密
        /// </summary>
        /// <param name="encryptText"></param>
        /// <returns></returns>
        public static string Encrypt(string encryptText)
        {
            return EncryptString(encryptText);
        }

        private static string EncryptString(string encryptText)
        {
            byte[] textBuf = Encoding.UTF8.GetBytes(encryptText.ToString());
            byte[] encryptBuf;
            DES des = new DESCryptoServiceProvider();
            ICryptoTransform encryptor = des.CreateEncryptor(cryptKey, cryptIV);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write);
            cs.Write(textBuf, 0, textBuf.Length);
            cs.FlushFinalBlock();
            encryptBuf = ms.ToArray();
            cs.Close();
            ms.Close();
            return Convert.ToBase64String(encryptBuf).Replace("+", "%2B").Replace("/", "%2F");
        }
        /// <summary>
        /// 固定密钥解密
        /// </summary>
        /// <param name="decryptText"></param>
        /// <returns></returns>
        public static string Decrypt(string decryptText)
        {
            try
            {
                decryptText = decryptText.Replace("%2B", "+").Replace("%2F", "/").Replace(" ", "+");
                byte[] encryptBuf = Convert.FromBase64String(decryptText);
                byte[] decryptBuf = new byte[encryptBuf.Length];
                DES des = new DESCryptoServiceProvider();
                ICryptoTransform decryptor = des.CreateDecryptor(cryptKey, cryptIV);
                MemoryStream ms = new MemoryStream(encryptBuf);
                CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read);
                int length = cs.Read(decryptBuf, 0, decryptBuf.Length);
                cs.Close();
                ms.Close();
                if (length < encryptBuf.Length)
                {
                    byte[] decryptBuf2 = new byte[length];
                    for (int i = 0; i < length; i++)
                    {
                        decryptBuf2[i] = decryptBuf[i];
                    }
                    return Encoding.UTF8.GetString(decryptBuf2);
                }
                else
                {
                    return Encoding.UTF8.GetString(decryptBuf);
                }
            }
            catch
            {
                throw new Exception("encrypt");
            }
        }

        ///MD5加密
        public static string MD5Encrypt(string pToEncrypt, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
            des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            ret.ToString();
            return ret.ToString();


        }


        public static byte[] Md5(string encryptText)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] result = md5.ComputeHash(Encoding.UTF8.GetBytes(encryptText));
            return result;
        }
        public static bool Equal(byte[] buf1, byte[] buf2)
        {
            if (Encoding.UTF8.GetString(buf1) == Encoding.UTF8.GetString(buf2))
            {
                return true;
            }
            return false;
        }

        public static string Encode(int val)
        {
            return Encode(val.ToString());
        }

        public static string Encode(string str)
        {
            byte[] buf = Encoding.UTF8.GetBytes(str);
            string returnString = "";
            for (int i = 0; i < buf.Length; i = i + 8)
            {
                byte[] _buf = new byte[8];
                if (buf.Length < i + 8)
                {
                    Array.Copy(buf, i, _buf, 0, buf.Length % 8);
                }
                else
                {
                    Array.Copy(buf, i, _buf, 0, 8);
                }
                ulong l = BitConverter.ToUInt64(_buf, 0);
                if (l.ToString().Length.ToString().Length == 1)
                {
                    returnString += "0" + l.ToString().Length + l.ToString();
                }
                else
                {
                    returnString += l.ToString().Length + l.ToString();
                }
            }
            return returnString;
        }

        public static string Decode(string str)
        {
            List<byte> list = new List<byte>();
            for (int i = 0; i < str.Length; i++)
            {
                int head = Convert.ToInt32(str[i].ToString() + str[i + 1].ToString());
                ulong l = Convert.ToUInt64(str.Substring(i + 2, head));
                byte[] buf = BitConverter.GetBytes(l);
                list.AddRange(buf);
                i = i + head + 1;
            }
            byte[] _buf = list.ToArray();
            return Encoding.UTF8.GetString(_buf).TrimEnd('\0');
        }

        public static string CreateNonceStr(int length = 16)
        {
            return Guid.NewGuid().ToString().Replace("-", "").Substring(0, length > 32 ? 32 : length);
        }
    }

}